import {
    Config
} from './config'
class Token {
    constructor() {
        this.tokenUrl = Config.baseUrl + 'token/user'
    }

    /**
     * 验证token
     */
    verify() {
        let that = this,
            token = wx.getStorageSync('token')
        if (!token) {
            that.getTokenFromServer()
        } else {
            that._veirfyFromServer(token)
        }
    }

    /**
     * 从服务器验证令牌
     * @param {string} token 令牌
     */
    _veirfyFromServer(token) {
        let that = this
        wx.request({
            url: Config.baseUrl + 'token/verify',
            method: 'POST',
            data: {
                token: token
            },
            success: (res) => {
                let valid = res.data.isValid
                if (!valid) {
                    that.getTokenFromServer()
                }
            }
        })
    }

    /**
     * 从服务器获取令牌
     */
    getTokenFromServer() {
        let that = this
        return new Promise((resolve, reject) => {
            wx.login({
                success: (res) => {
                    if (res.code) {
                        wx.request({
                            url: that.tokenUrl,
                            method: 'POST',
                            data: {
                                code: res.code
                            },
                            success: (res) => {
                                wx.setStorageSync('token', res.data.token)
                                resolve(res)
                            }
                        })
                    } else {
                        console.error(res)
                        reject(res)
                    }
                }
            })
        })
    }
}

export {
    Token
}